package com.starking.wxx.job;

import com.alibaba.fastjson.JSON;
import com.starking.wxx.mybatis.dao.UserAuthEntityMapper;
import com.starking.wxx.mybatis.entity.UserAuthEntity;
import com.starking.wxx.util.ToolUtils;
import com.starking.wxx.weixin.AutoAward;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @描述: 微信自动抽奖job
 * @文件名: WeixinAuthGetAwardJob.java
 * @创建人: wangxinxin
 * @创建时间: 2018/11/8
 * @修改人: wangxinxin
 * @修改备注: <br/>
 * <p>
 * Copyright 西安创意 2018/11/08
 */
public class WeixinAuthGetAwardJob implements Job {
    //job执行状态
    private static boolean isRun = false;
    private static int AUTH_STATUS_USE = 1;//使用中

    public static final Logger LOGGER = LoggerFactory.getLogger(WeixinAuthGetAwardJob.class);

    @Resource
    private UserAuthEntityMapper userAuthEntityMapper;

    //认证
//    static String auth = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMjQxNDc2NywiaWF0IjoxNTQ1MTQwODY2LCJleHAiOjE1NDU3NDU2NjZ9.WxrDpB2vspXzcPcuafdx407geDSos7yD9R8l861uxG4";
//    static String auth = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxNjA0Mzk2MjEsImlhdCI6MTU0NTE0OTA4NiwiZXhwIjoxNTQ1NzUzODg2fQ.jq9EcyBGIiJSKNwR10TvpZqxE8Ab9KN4iqoWU9qzZRs";

    private static int page = 1;//活动页数

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        if (isRun) {
            LOGGER.info("job is run.......");
            return;
        }

        isRun = true;

        // 判断时间允许
        if (judgeTime()) {


            List<UserAuthEntity> userAuthEntities = userAuthEntityMapper.selectAll();
            LOGGER.info("userAuthEntities = {}", JSON.toJSONString(userAuthEntities));

            if (ToolUtils.listIsNotEmpty(userAuthEntities)) {
                for (UserAuthEntity userAuthEntity : userAuthEntities) {
                    if (userAuthEntity.getAuthStatus() == AUTH_STATUS_USE) {
                        LOGGER.info("start execute auto join award! userAuthEntity = {}", JSON.toJSONString(userAuthEntity));
                        executeOne(userAuthEntity.getAuth());
                    }else{
                        LOGGER.info("the user status={} is error! I ignore it and run next! ignore userAuthEntity = {}", userAuthEntity.getAuthStatus(), JSON.toJSONString(userAuthEntity));
                    }
                }
            }

        }

        isRun = false;

    }

    /**
     * 时间规则：
     * 1.60分钟内随机执行一次
     * 2.晚上12点后，早上9点前不执行
     * 3.
     */
    private boolean judgeTime() {

        //随机休眠
        Random random = new Random();
        int nextInt = random.nextInt(60);
        LOGGER.info("I start sleep {} minutes", nextInt);
        try {
            Thread.sleep(nextInt * 60 * 1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        Date now = new Date();
        String today = ToolUtils.getDateStr(now);
        Date after9 = ToolUtils.formatDateStr(today + " 09:00:00", "yyyy-MM-dd HH:mm:ss");
        if (now.before(after9)) {
            LOGGER.info("now is {} ,can not run this job!!!", ToolUtils.getDateStr());
            return false;
        }

        LOGGER.info("now is {} ,i can run this job!!!", ToolUtils.getDateStr());
        return true;
    }


    private void executeOne(String auth) {
        LOGGER.info("start join! page={}", page);
        List<AutoAward.WeixinPriceAct> weixinPriceActs = AutoAward.queryAwardActList(auth, page);
        if (ToolUtils.listIsEmpty(weixinPriceActs)) {
            LOGGER.info("query act list is empty! stop join!");
            return;
        }

        //遍历活动，去参与
        for (AutoAward.WeixinPriceAct priceAct : weixinPriceActs) {
            if ("true".equals(priceAct.getJoined())) {

                LOGGER.info("actid = {} has join success!", priceAct.getId());
            } else {

                //未参与成功
                AutoAward.autoJoinAct(auth, priceAct.getId());

                //自动休眠,随机10分钟
                Random random = new Random();
                int sleepMinute = random.nextInt(5);
                LOGGER.info("i will sleep {} minutes!", sleepMinute);
                try {
                    Thread.sleep(sleepMinute * 60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        LOGGER.info("page={} has execute end!", page);

//        page++;
//        executeOne();
    }
}
